package linkedlist.test92;

import listbyorder.utils.ListNode;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/14 13:50
 */
public class Solution1 {

    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (m == n) return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode s = dummy, t = dummy;
        while (m - 1 > 0) {
            s = s.next;
            m--;
        }
        while (n > 0) {
            t = t.next;
            n--;
        }
        ListNode tail = t.next;
        t.next = null;
        ListNode rT = s.next;
        s.next = reverse(rT);
        rT.next = tail;
        return dummy.next;
    }

    private ListNode reverse(ListNode node) {
        ListNode pre = null;
        ListNode next;
        while (node != null) {
            next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }
        return pre;
    }
}
